
import 'dart:async';

import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:get/get.dart';
import 'package:step_progress_indicator/step_progress_indicator.dart';
import '../entity/book_entity.dart';
import '../event/inventory_event.dart';
import '../main.dart';
import '../util/analysis_book_rule.dart';
import '../widget/dialog.dart';

class Position extends StatefulWidget {
  const Position({Key? key}) : super(key: key);

  @override
  State<Position> createState() => _PositionState();
}

class _PositionState extends State<Position> {

  late BookEntity entity;

  StreamSubscription? subscription;

  RxInt rssi = RxInt(0);
  RxString distance = RxString('');

  int dis = settingEntity.distance??30;

  @override
  initState() {
    super.initState();
    entity = Get.arguments;
    subscription = eventFactory.on<InventoryEvent>().listen((event) {
      var no = analysisBookNoRule(event.data);
      if(no == null || no.isEmpty){
        return;
      }
      _analyze(no,event.data);
    });
    player.play('audio/scan_book.mp3');
  }

  @override
  void dispose() {
    subscription?.cancel();
    subscription = null;
    super.dispose();
  }

  _analyze(String no, String epc){
    try{
      if(no == entity.no!){
        var value =  double.tryParse(epc.split('-')[1]);
        if(value != null){
          rssi.value = value.toInt();
          if(rssi.value> 50){
            distance.value = '1米以上';
          }else{
            if(value>dis){
              distance.value = "${(value.toInt()-dis).toString()}厘米附近";
            }else{
              distance.value = '1厘米附近';
            }
          }
        }
      }
    }catch(e){
      print(e);
    }
  }

  _title(){
    return Container(
        margin: EdgeInsets.only(top: 30.h),
        child: Row(
          mainAxisAlignment: MainAxisAlignment.spaceBetween,
          crossAxisAlignment: CrossAxisAlignment.center,
          children: [
            InkWell(
              onTap: (){
                Get.back();
              },
              child: Row(
                children: [
                  const Icon(Icons.arrow_back_ios_new,color: Colors.white,),
                  Text("返回",style: TextStyle(color: Colors.white,fontSize: 16.sp),)
                ],
              )
            ),
            Image.asset("assets/images/query_title.png",width: 100.w,fit: BoxFit.fitWidth,),
            InkWell(
              onTap: (){
                DialogWidget().settingDialog();
              },
              child: Text("调整功率",style: TextStyle(color: Colors.white,fontSize: 16.sp),),
            )
          ],
        )
    );
  }

  _listItem(item){
    return Container(
      margin: EdgeInsets.only(top: 10.r),
      decoration: BoxDecoration(
        color: Colors.white,
        borderRadius: BorderRadius.all(Radius.circular(6.r)),
      ),
      padding: EdgeInsets.all(10.r),
      child: Column(
        children: [
          InkWell(
            onTap: (){

            },
            child: Row(
              mainAxisAlignment: MainAxisAlignment.spaceBetween,
              children: [
                SizedBox(width: 230.w,child:Text('${item.mainTitle}',maxLines: 1,overflow: TextOverflow.ellipsis,),),
                Image.asset("assets/images/position.png",width: 50.w,fit: BoxFit.fitWidth,),
              ],
            ),
          ),
          Column(
            mainAxisAlignment: MainAxisAlignment.start,
            children: [
              SizedBox(height: 6.h,),
              Divider(height: 0.5.h, indent: 4.w, endIndent: 4.w, color: const Color.fromRGBO(86, 169, 255, 1),),
              SizedBox(height: 6.h,),
              Row(
                children: [
                  const Text('存放位置：'),
                  Text('${item.placeName}',style: const TextStyle(color: Color.fromARGB(255, 20, 196, 196)),),
                ],
              ),
              Row(
                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                children: [
                  Text('条码号：${item.no}'),
                  Text('索书号：${item.searchNo}'),
                ],
              )
            ],
          )
        ],
      )
    );
  }


  _positionWidget(){
    return Container(
      width: double.infinity,
      height: 420.h,
      margin: EdgeInsets.only(top: 10.r),
      decoration: BoxDecoration(
        color: Colors.white,
        borderRadius: BorderRadius.all(Radius.circular(6.r)),
      ),
      child: Stack(
        alignment: AlignmentDirectional.center,
        children: [
          Image.asset("assets/images/progress.png",width: 290.w,fit: BoxFit.fitWidth,),
          Obx(() => CircularStepProgressIndicator(
            totalSteps: 100,
            currentStep: 130-rssi.value>100?100:130-rssi.value,
            selectedColor: Colors.blue,
            unselectedColor: const Color.fromARGB(255, 204, 221, 255),
            padding: 0,
            width: 170,
            height: 170,
            stepSize: 10,
            selectedStepSize: 15,
            roundedCap: (_, __) => true,
          )),
          Column(
            mainAxisAlignment: MainAxisAlignment.center,
            children: [
              Obx(() => Text.rich(
                TextSpan(
                  children: [
                    TextSpan(text: "${rssi.value}", style: TextStyle(color: Colors.blue,fontSize: 30.sp)),
                    TextSpan(text: "dBm", style: TextStyle(color: Colors.blue,fontSize: 10.sp),),
                  ],
                ),
              )),
              Obx(() => Text(distance.value, style: TextStyle(color: Colors.blue,fontSize: 20.sp))),
            ],
          ),
          Positioned(
            top: 350.h,
            child: InkWell(
              onTap: (){
                Get.back();
              },
              child: Image.asset("assets/images/confirm.png",width: 120.w,fit: BoxFit.fitWidth,),
            ),
          ),

        ],
      ),
    );
  }

  //5 30-50


  @override
  Widget build(BuildContext context) {
    return Scaffold(
      resizeToAvoidBottomInset: false,
      body: Container(
        width: double.infinity,
        height: double.infinity,
        padding: EdgeInsets.only(left: 20.r,right: 20.r),
        decoration: const BoxDecoration(
          image: DecorationImage(
            fit: BoxFit.fill,
            image: AssetImage(
              "assets/images/bg.png",
            ),
          ),
        ),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.center,
          children: [
            _title(),
            SizedBox(height: 30.h,),
            _listItem(entity),
            _positionWidget()
          ],
        )
      ),
    );
  }
}